package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.behavior.service.ApBehaviorService;
import com.heima.behavior.service.ApCollectionBehaviorService;
import com.heima.model.article.dto.CollectionBehaviorDto;
import com.heima.model.behavior.pojo.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.ApUserThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class ApConllectionBehaviorServiceImpl implements ApCollectionBehaviorService {

    @Autowired
    ApBehaviorService behaviorService;

    @Autowired
    KafkaTemplate kafkaTemplate;
    /**
     * 收藏行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        //检查数据
        if (dto == null || dto.getEntryId() == null || dto.getOperation() == null || dto.getType() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = ApUserThreadLocalUtils.getUser();
        if (dto.getEquipmentId() == null && user == null || user.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getEquipmentId() == null) {
            dto.setEquipmentId(user.getId());
        }


        //查询实体对象，如果不存在则返回
        ApBehaviorEntry behaviorEntry = behaviorService.getOne(Wrappers.<ApBehaviorEntry>lambdaQuery().eq(ApBehaviorEntry::getEntryId, dto.getEquipmentId()));
        if (behaviorEntry==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //发送异步请求kafka
        dto.setEquipmentId(behaviorEntry.getEntryId());

        return ResponseResult.okResult(kafkaTemplate.send("collection", JSON.toJSONString(dto)));
    }
}
